<?php
/**
 * @package me.joshua.proj4j.baehelper
 *
 * BAE Helper core functions.
 */

/**
 * Send Mail via the API of BCMS.
 * Overwrite the function defined in @see wp-includes/pluggable.php
 */
if (!function_exists('wp_mail') && class_exists('Bcms')) :
function wp_mail($to, $subject, $message, $headers = '', $attachments = array()) {

	$settings = bae_helper_bcms_get_options();
	$queue_name = $settings['bcms-queue-name'];
	if (empty($queue_name)) {
		// BCMS queue name is not set, just return.
		return FALSE;
	}

	// Compact the input, apply the filters, and extract them back out
	extract(apply_filters('wp_mail', 
			compact('to', 'subject', 'message', 'headers', 'attachments')));

	// Set destination addresses
	if (!is_array($to))
		$to = explode(',', $to);

	foreach ((array) $to as $recipient) {
		// Break $recipient into name and address parts if in the format 
		// "Foo <bar@baz.com>"
		$recipient_name = '';
		if (preg_match('/(.*)<(.+)>/', $recipient, $matches)) {
			if (count($matches) == 3) {
				$recipient = $matches[2];
			}
		}
	}

	// The BCMS SDK is within the PHP runtime already.
	$bcms = new Bcms();
	$ret = $bcms -> mail($queue_name, $message, $to, 
			array(Bcms::MAIL_SUBJECT => $subject));
	if (FALSE === $ret) {
		return FALSE;
	} else {
		return TRUE;
	}
}
endif;

function bae_helper_bcms_get_options() {
	global $settings;
	if (!isset($settings)) {
		$settings = get_option('bae-helper-settings');
	}
	return $settings;
}

/**
 * Add custom content in the head of page.
 */
function bae_helper_custom_head() {
	$settings = bae_helper_bcms_get_options();
	echo $settings['page-custom-head'];
}

/**
 * Add custom content in the footer of page.
 */
function bae_helper_custom_footer() {
	$settings = bae_helper_bcms_get_options();
	echo $settings['page-custom-footer'];
}

/**
 * Replace the Gravatar host to DuoShuo's gravatar proxy, in case the original 
 * host is blocked.
 */
function bae_helper_gravatar_proxy($avatar) {
	$avatar = str_replace(array('www.gravatar.com', '0.gravatar.com', 
			'1.gravatar.com', '2.gravatar.com'), 'gravatar.duoshuo.com', $avatar);
	return $avatar;
}

/**
 * Debug function for BAE Helper,
 */
function bae_helper_debug($message) {
	if (!WP_DEBUG) {
		return;
	}

	global $bae_logger;

	if (class_exists('BaeLog')) {
		if (!isset($bae_logger)) {
			$bae_logger = BaeLog::getInstance();
		}
		$bae_logger -> logDebug('[BAE Helper]: ' . $message . '\n');
	} else {
		error_log($message);
	}
}
